<template>
<l-layout >
    <l-panel style="padding:0;" >
        <template #toolLeft >
            <div class="l-panel--item" >
                <el-input :placeholder="$t('请输入名称/编号')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                    <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                </el-input>
            </div>
        </template>
        <template #toolRight >
            <el-button-group>
                <el-button size="mini" icon="el-icon-refresh-left" @click="handleRefresh"></el-button>
            </el-button-group>
            <el-button-group>
                <el-button type="primary" size="mini" icon="el-icon-plus"
                    @click="handleAdd()"
                >{{$t('新增')}}</el-button>
            </el-button-group>
        </template>
        <l-table 
            :columns="columns" 
            :dataSource="tableData" 
            :loading="tableLoading"
            row-key="f_Id"
            :isPage="true"
            :pageTotal="tableTotal"
            >
            <template v-slot:f_CreateDate="scope" >
                {{lr_dateFormat(scope.row.f_CreateDate)}}
            </template>
            <l-table-btns :btns="tableBtns" @click="handleBtnClick" ></l-table-btns>
        </l-table>
    </l-panel>

    <l-dialog
        :title="formTitle"
        :visible.sync="formVisible"

        width="720px"
        @close="handleCloseForm"
        @ok="handleSave"
        >
        <div class="l-from-body" > 
            <el-form :model="formData" size="mini" :rules="rules"  ref="form" label-width="56px"  >
                <el-col :span="12">
                    <el-form-item label="编码" prop="f_Code">
                        <el-input v-model="formData.f_Code"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="名称" prop="f_Name">
                        <el-input v-model="formData.f_Name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" style="padding-left:34px;">
                    <draggable
                        :list="conditions"
                        :group="{ name: 'dic' }"
                        ghost-class="set-item-ghost"
                        handle=".l-drag-item">
                        <div v-for="(item, index) in conditions"
                            class="l-set-item l-set-item__Num" 
                            :key="index">
                            <i class="l-drag-item el-icon-rank"></i>
                            <el-tag type="info" size="medium" effect="plain">{{index + 1}}</el-tag>
                            <el-input
                                style="width:26%;margin-right:1%;"
                                size="mini"
                                v-model="item.F_FieldId"
                                placeholder="字段"></el-input>
                            <l-select style="width:19%;margin-right:1%;"
                                size="mini"
                                v-model="item.F_Symbol"
                                :placeholder="$t('比较符')"
                                :options="symbolOptions"
                                >
                            </l-select>
                            <l-select style="width:26%;margin-right:1%;"
                                size="mini"
                                v-model="item.F_FiledValueType"
                                :placeholder="$t('字段值类型')"
                                :options="vTypeOptions"

                                @change="handleChangeVType(item)"
                                >
                            </l-select>
                            <el-input
                                :readonly="item.F_FiledValueType != 1 && item.F_FiledValueType != 10 "
                                style="width:26%;"
                                size="mini"
                                v-model="item.F_FiledValue"
                                placeholder="字段值"></el-input>
                            <el-button 
                                @click="handleRemoveConditions(index)"
                                circle
                                plain
                                type="danger"
                                size="mini"
                                icon="el-icon-minus"
                                class="l-delete-item"
                                style="padding: 4px;"></el-button>
                        </div>
                    </draggable>
                    <div style="padding-left:22px;" >
                        <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handleAddConditions"  >添加过滤条件</el-button>
                    </div>
                </el-col>  
                <el-col :span="24">
                    <el-form-item label="公式" prop="f_Formula">
                        <el-input v-model="formData.f_Formula" placeholder="请输入公式,默认为 1 and 2 and 3 这种且方式">

                            <el-popover
                                slot="append"
                                placement="bottom"
                                width="240"
                                trigger="hover">

                                <div class="info-message">
                                    <p>请按如下规则编辑条件组合</p>
                                    <p class="ok">(1 and 2) or (3 and 4) <i class="fa fa-check"></i></p>
                                    <p>1.有and和or必须加括号</p>
                                    <p class="error">1 and 2 or 3 and 4 <i class="fa fa-close"></i></p>
                                    <p>2.一个括号里不能同时出现and和or</p>
                                    <p class="error">(1 and 2 or 3 )and 4 <i class="fa fa-close"></i></p>
                                    <p>3.不允许出现不存在的编号</p>
                                    <p class="error">1 and 2 and 3 and 4 and 5 <i class="fa fa-close"></i></p>
                                    <p>4.括号都是成对出现的</p>
                                    <p class="error">(1 and 2 and 3 and 4 <i class="fa fa-close"></i></p>
                                </div>    
                                <el-button  slot="reference" icon="el-icon-question"></el-button>
                            </el-popover>
                           
                        </el-input>
                    </el-form-item>
                </el-col>  


  
            </el-form>
        </div>
    </l-dialog>
</l-layout>
</template>

<script>
//import { getDataAuthorizePage,addDataAuthorize,updateDataAuthorize,deleteDataAuthorize } from '@/api/authorize/dataAuthorize.js';

export default {
  name:'data-authorize',
  props: {
  },
  data () {
    return {
        searchWord:'',
        
        columns: [
            {label:'编码',prop:'f_Code',minWidth:'120'},
            {label:'名称',prop:'f_Name',minWidth:'160'},
            {label:'创建人',prop:'f_CreateUserName',width:'100'},
            {label:'创建时间',prop:'f_CreateDate',width:'140'}
        ],
        tableBtns:[
            {prop:'edit',label:'编辑'},
            {prop:'delete',label:'删除'}
        ],
        tableLoading:false,
        tableData:[],
        tableTotal:0,
        tablePageSize:50,
        tableCurrentPage:1,

        objectId:'',
        objectType:0,

        formTitle:'',
        formVisible:false,
        formEdit:false,
        formData:{
            f_Code: '',
            f_Name: '',
            f_Formula: ''
        },
        rules: {
            f_Code: [
                { required: true, message: '请输入编码' }
            ],
            f_Name: [
                { required: true, message: '请输入名称' }
            ]
        },
        symbolOptions:[
            { value: 1, label: '等于' }, 
            { value: 2, label: '大于' }, 
            { value: 3, label: '大于等于' }, 
            { value: 4, label: '小于' },
            { value: 5, label: '小于等于' },
            { value: 6, label: '包含' }, 
            { value: 7, label: '包含于' }, 
            { value: 8, label: '不等于' },
            { value: 9, label: '不包含' },
            { value: 10, label: '不包含于' }],
        vTypeOptions:[
            { value: 1, label: '文本(String)' }, 
            { value: 10, label: '文本(Int)' }, 
            { value: 2, label: '登录者ID' }, 
            { value: 3, label: '登录者账号' },
            { value: 4, label: '登录者公司' }, 
            { value: 41, label: '登录者公司及下属公司' }, 
            { value: 5, label: '登录者部门' }, 
            { value: 51, label: '登录者部门及下属部门' },
            { value: 6, label: '登录者岗位' }, 
            { value: 7, label: '登录者角色' }
        ],

        conditions:[]
    };
  },
  created () {
  },
  mounted () {
  },
  computed:{
    dataItemClassifysTree(){
        return this.$toTree(this.$store.state.dataItem.dataItemClassifys,"f_ItemId","f_ParentId","f_ItemId","f_ItemName")
    }
  },
  methods:{
    setIndex(objectId,objectType){
        this.objectId = objectId;
        this.objectType = objectType;
        this.tableLoadData();
    },
    tableLoadData(){
        this.tableLoading = true;
        let queryData = {
            rows:this.tablePageSize,
            page:this.tableCurrentPage,
            sidx:'F_CreateDate DESC',
            keyword:this.searchWord,
            type:1,
            objectId:this.objectId
        }
        getDataAuthorizePage(queryData).then(res=>{
            const data = this.$deepClone(res.data.data);
            this.tableData = data.rows;
            this.tableTotal = data.records;
            this.tableLoading = false;

        }).catch(()=>{
            this.tableData = [];
            this.tableLoading = false;
        });
    },
    handleRefresh(){
        this.tableLoadData();
    },
    hanleSearch(){
        this.tableLoadData();
    },
    handleBtnClick(btn){
        switch(btn.type){
            case 'edit':
                this.handleEdit(btn.rowIndex,btn.row);
                break;
            case 'delete':
                this.handleDelete(btn.rowIndex,btn.row);
                break; 
        }
    },
    handleAdd(){
        this.formEdit = false;
        this.showForm('新增数据权限条件');
    },
    handleEdit($index,row){  
        this.formEdit = true;
        let formData = this.$deepClone(row);
        let formula = JSON.parse(formData.f_Formula);
        formData.f_Formula = formula.formula;
        this.conditions = formula.conditions;
        this.formData = formData;
        this.showForm('编辑数据权限条件');
    },
    handleDelete($index,row){
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deleteDataAuthorize(row.f_Id).then(()=> {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.handleRefresh();
            }).catch(() => {
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    handleSave(showLoading,hideLoading){
        this.$refs.form.validate((valid)=>{
            if(valid){

                // 判断设置条件是否完善
                this.conditions.forEach(item => {
                    if(this.$validatenull(item.F_FieldId)){
                        this.$message({
                            type: 'error',
                            message: '请填写过滤条件字段!'
                        });
                        valid = false;
                        return false;
                    }
                    if(this.$validatenull(item.F_Symbol)){
                        this.$message({
                            type: 'error',
                            message: '请选择过滤条件比较符!'
                        });
                        valid = false;
                        return false;
                    }
                    if(this.$validatenull(item.F_FiledValueType)){
                        this.$message({
                            type: 'error',
                            message: '请选择过滤条件字段值类型!'
                        });
                        valid = false;
                        return false;
                    }
                    if(this.$validatenull(item.F_FiledValue)){
                        this.$message({
                            type: 'error',
                            message: '请填写过滤条件字段值!'
                        });
                        valid = false;
                        return false;
                    }
                });
                if(!valid){
                    return;
                }

                showLoading();
                const postData = this.$deepClone(this.formData);
                postData.F_Type = 1;
                let formula = {
                    formula: postData.f_Formula,
                    conditions: this.conditions
                };
                postData.f_Formula = JSON.stringify(formula);
                postData.f_ObjectId = this.objectId;
                postData.f_ObjectType = this.objectType;

                if(this.formEdit){// 修改数据
                    updateDataAuthorize(postData.f_Id,postData).then(()=> {
                        hideLoading();
                        this.formVisible = false;
                        this.handleRefresh();
                        this.$message({
                            type: 'success',
                            message: '更新成功!'
                        });
                    }).catch(() => {
                        hideLoading();
                    })
                }
                else{// 新增数据
                    addDataAuthorize(postData).then(()=> {
                        hideLoading();
                        this.formVisible = false;
                        this.handleRefresh();
                        this.$message({
                            type: 'success',
                            message: '新增成功!'
                        });

                    }).catch(() => {
                        hideLoading();
                    })
                }
            }
        });
    },
    handleCloseForm(){
        this.formData.f_Id = '';
        this.conditions = [];
        this.$refs.form && this.$refs.form.resetFields();
    },
    showForm(text){
        this.formTitle = text;
        this.formVisible = true;
    },
    handleAddConditions(){
        this.conditions.push({F_FieldId:'',F_Symbol:1,F_FiledValueType:1,F_FiledValue:''});
    },
    handleRemoveConditions(index){
        this.conditions.splice(index,1);
    },
    handleChangeVType(item){
        if(item.F_FiledValueType == 1 || item.F_FiledValueType == 10){
            item.F_FiledValue = '';
        }
        else{
          item.F_FiledValue = this.vTypeOptions.find(t=>t.value == item.F_FiledValueType ).label;
        }
    }
  }
}
</script>
